package product

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func detail(r *gin.RouterGroup) {
	detail := r.Group("/detail")
	{
		detail.GET(sql.RequestList, productDetailList)
		detail.GET(sql.RequestData, productDetailData)
		detail.GET(sql.RequestDelete, productDetailDelete)
		detail.POST(sql.RequestAdd, productDetailAdd)
		detail.POST(sql.RequestUpdate, productDetailUpdate)
	}
}

func productDetailAdd(c *gin.Context) {
	productDetailEdit(sql.ADD, c)
}

func productDetailUpdate(c *gin.Context) {
	productDetailEdit(sql.UPDATE, c)
}

func productDetailData(c *gin.Context) {
	sql.HttpHandle(sql.GET, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		var product model.ProductDetail
		id := c.Query("id")
		db.Where("id = ?", id).First(&product)
		//product.ImageList = sql.StrFormatList(product.Images)
		product.Images = ""
		return db, product
	})
}

func productDetailDelete(c *gin.Context) {
	sql.HttpHandle(sql.DELETE, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		id := c.Query("id")
		db.Where("id = ?", id).Delete(&model.ProductDetail{})
		return db, nil
	})

}

func productDetailList(c *gin.Context) {
	sql.HttpHandle(sql.GET, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		factoryNo := c.Query("factoryNo")
		productName := c.Query("productName")
		productNo := c.Query("productNo")
		if factoryNo != "" {
			db = db.Where("factory_no = ?", factoryNo)
		}
		if productName != "" {
			db = db.Where("product_name = ?", productName)
		}
		if productNo != "" {
			db = db.Where("product_no = ?", productNo)
		}
		var detailList []model.ProductDetail
		db.Find(&detailList)
		/*for i, detail := range detailList {
			detailList[i].ImageList = sql.StrFormatList(detail.Images)
			detailList[i].Images = ""
		}*/
		return db, detailList

	})

}

func productDetailEdit(text string, c *gin.Context) {
	sql.HttpHandle(text, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		var bean model.ProductDetail
		if err := sql.PostParamsBind(c, db, &bean).Error; err != nil {
			return db, nil
		}
		productName := c.PostForm("productName")
		path := "product/" + productName + bean.ProductDate
		bean.Images = sql.ImageSave(c, path)
		if bean.Images == "" {
			db.Error = errors.New(sql.ErrorParams)
			return db, nil
		}
		if text == sql.ADD {
			bean.Id = 0
			db = db.Create(&bean)
		} else if text == sql.UPDATE {
			db = db.Updates(&bean)
		}
		/*bean.ImageList = sql.StrFormatList(bean.Images)
		bean.Images = ""*/
		return db, bean
	})
}
